local app = require "app"
local game = require "club.threecard.hbsl"
local LoopScrollList = require "blaze.ui.widget.LoopScrollList"

local M = game.ui.element()

M.store_watchers = {
    self_record = {
        ["记录变更"] = function(self, stroe, state, args, init)
            if init then
                return
            end
        end
    }
}

local LeftItem = game.ui.element()

function LeftItem:ctor(list_left, list_right)
    self.list_right = list_right
    self.list_left = list_left
    local avatar_icon = require "ui.Common.AvatarIcon"
    self.avatar = avatar_icon.new()
end

function LeftItem:on_scroll_cell_update(data, index)
    self.data = data
    self.index = index
    self.name_txt.text = data.sender.name
    self.no_txt.text = data.no
    self.amount_txt.text = app.i18n.number(data.amount, "chip4")
    self.avatar:set_head(data.sender.head)
    self.avatar:set_flag(data.sender.country)
end

function LeftItem:on_injected(bind)
    bind("button.click", self.btn_click, self.on_click)
    self.avatar:set_gameobject(self.avatar_obj, true)
end

function LeftItem:on_select(b)
    self.bg_selected:SetActive(b)
    self.bg_normal:SetActive(not b)
end

function LeftItem:on_click()
    self.list_right:fill(self.data.players)
    self:on_select(true)
    game.audio.post("hbsl:click")

    for _, item in pairs(self.list_left.map) do
        if item ~= self then
            item:on_select(false)
        end
    end
end

local RightItem = game.ui.element()

function RightItem:on_scroll_cell_update(data, index)
    self.name_txt.text = data.name
    self.amount_txt.text = data.amount

    self.flag_self:SetActive(data.id == game.kbe.player().id)
    self.flag_bomb:SetActive(data.is_hit)
    self.flag_crown:SetActive(data.is_crown)
end

function M:ctor()
    self.res = "club.threecard.hbsl/ui/ingame.b:self_record"

    self.list_right = LoopScrollList.new()
    self.list_right.res = "club.threecard.hbsl/ui/ingame.b:right_temp"
    self.list_right.create_item = function(_, data, index) return RightItem.new() end

    self.list_left = LoopScrollList.new()
    self.list_left.res = "club.threecard.hbsl/ui/ingame.b:left_temp"
    self.list_left.create_item = function(_, data, index) return LeftItem.new(self.list_left, self.list_right) end
end

function M:on_load()
    self:super("on_load")
    self.list_right:load()
    self.list_left:load()
end

function M:on_injected(bind)
    self.list_left:attach(self.left_scroll)
    self.list_right:attach(self.right_scroll)
    bind("button.click", self.btn_close, self.close_ivk)
    bind("button.click", self.btn_mask, self.close_ivk)
end

function M:close_ivk()
    self:hide()
end

function M:show()
    self:super("show")
    local records = game.store.self_record.state.records
    if #records < 1 then
        return
    end

    self.list_left:fill(records)
    for _, item in pairs(self.list_left.map) do
        if item.index == 1 then
            item:on_click()
        end
    end
end

return M